
package com.x52im.mall.logic.shop;

import java.text.MessageFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.eva.android.widget.AListAdapter2;
import com.eva.framework.dto.DataFromClient;
import com.eva.framework.dto.DataFromServer;
import com.eva.framework.dto.SysActionConst;
import com.x52im.mall.IntentFactory;
import com.x52im.mall.ObjectFactory;
import com.x52im.mall.dto.CommonProcessorConst;
import com.x52im.mall.shop.dto.JobDispatchConst;
import com.x52im.mall.shop.dto.SO;
import com.x52im.mall.shop.dto.SODetail;
import com.x52im.rbchat.R;
import com.x52im.mall.MallGlobal;
import com.x52im.mall.Utility;
import com.eva.android.widget.DataLoadableActivity;

/**
 * 
 * @author Jason
 * 
 */
public class OrderConfirmDetailActivity extends DataLoadableActivity
{

	public static final int REQUEST_COMMENT_RESULT_INFO = 999;
	
	private SO so = null;
	
	private SODetail soDetail = null;
	
	private TextView orderNoView = null;
	
	private TextView orderCountView = null;
	
	private TextView orderStatusView = null;
	
	private TextView orderCurrencyView = null;
	
	private TextView totalView = null;
	
	private TextView addressView = null;
	
	private TextView consigneeView = null;
	
	private TextView orderTimeView = null;
	
	private TextView transferView = null;
	
	private ListView orderDetailListView = null;
	
	private DetailListAdapter detailListAdapter = null;
	
	private int current_position = 0;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void initDataFromIntent()
	{
		so = IntentFactory.parseOrderComfirmDetailActivityIntent(getIntent());
	}

	@Override
	protected void initViews(Bundle savedInstanceState)
	{
		customeTitleBarResId = R.id.common_mall_shop_layout_order_confirm_detail_titleBar;
		// 首先设置contentview
		setContentView(R.layout.common_mall_shop_layout_order_confirm_detail);
		
		orderNoView = (TextView) findViewById(R.id.common_mall_shop_layout_order_confirm_detail_order_id);
		orderCountView = (TextView) findViewById(R.id.common_mall_shop_layout_order_confirm_detail_sum);
		orderStatusView = (TextView) findViewById(R.id.common_mall_shop_layout_order_confirm_detail_status);
		orderCurrencyView = (TextView)findViewById(R.id.common_mall_shop_layout_order_confirm_detail_currency);
		totalView = (TextView) findViewById(R.id.common_mall_shop_layout_order_confirm_detail_total);
		addressView = (TextView) findViewById(R.id.common_mall_shop_order_confirm_detail_consignee_address);
		consigneeView = (TextView) findViewById(R.id.common_mall_shop_order_confirm_detail_consignee_name);
		orderTimeView = (TextView) findViewById(R.id.common_mall_shop_order_confirm_detail_create_time);
		transferView = (TextView) findViewById(R.id.common_mall_shop_order_confirm_detail_transfer_info);
		
		orderDetailListView = (ListView)findViewById(R.id.common_mall_shop_layout_order_confirm_detail_listview);
		detailListAdapter = new DetailListAdapter(this);
		orderDetailListView.setAdapter(detailListAdapter);
		
		Utility.setListViewHeightBasedOnChildren(orderDetailListView);
		
		setTitle(R.string.common_mall_shop_order_confirm_detail_title);
		
		orderNoView.setText(so.getOrder_id());
		orderCountView.setText(MessageFormat.format($$(R.string.common_mall_shop_order_confirm_detail_sum), getOrderDetailCount()));
		orderStatusView.setText(String.valueOf(ObjectFactory.createSOStatusRenderer(this).getNameById(so.getOrder_status())));
		orderCurrencyView.setText(String.valueOf(ObjectFactory.createCurrencyTypeRenderer().getNameById(so.getOrder_currency())));
		totalView.setText(so.getOrder_total());
		addressView.setText(so.getSoConsigneeInfo().getAddr_of_consignee());
		consigneeView.setText(so.getSoConsigneeInfo().getConsignee_name());
		orderTimeView.setText(so.getCreate_time());
		transferView.setText(so.getTransfer_id().equals("1") ? "UPS" : "Unknow Transfer");
		
	}

	@Override
	protected void initListeners()
	{
		
	}
	

	@Override
	protected DataFromServer queryData(String... arg0)
	{
		return MallGlobal.getMallProviderInstance(this).getRobotimeMall().getAuthedService().sendObjToServer(
				DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SHOP_NEED$AUTHED)
				.setJobDispatchId(JobDispatchConst.SHOP_GOODS_MGR_NEED$AUTHED)
				.setActionId(SysActionConst.ACTION_APPEND4)
				.setNewData(so.getOrder_id()));
	}

	@Override
	protected void refreshToView(Object dataToView)
	{
		ArrayList<SODetail> listData = (ArrayList<SODetail>) dataToView;
		detailListAdapter.setListData(listData);
		detailListAdapter.notifyDataSetChanged();
		Utility.setListViewHeightBasedOnChildren(orderDetailListView);
	}
	
	private int getOrderDetailCount()
	{
		int c = 0;
		if(so != null)
		{
			for(SODetail sd : so.getSoDetails())
			{
				c += Integer.parseInt(sd.getPurchase_quantity());
			}
			return c;
		}
		return c;
	}
	
	private class DetailListAdapter extends AListAdapter2<SODetail>
	{
		/** 记录选中的ListView的行索引值以备后用（目前是在：单击、长按2类事件中保存了此索引值）. */
		protected int selectedListViewIndex = -1;

		public DetailListAdapter(Activity context)
		{
			super(context, R.layout.common_mall_shop_layout_order_confirm_detail_list_item);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			TextView viewProName = null;
			TextView viewCurrency = null;
			TextView viewPrice = null;
			TextView viewCount = null;
			Button commentBtn = null;

			// ----------------------------------------------------------------------------------------
			// （1）UI初始化
			// 当的item布局实例已经存在（不在存，意味着这个item刚好从不可见区移到可见区时）
			// ** 根据android的列表ui实现，为了节比资源占用，假如列表有100行而可见区显示5行，那么任何时候
			// ** 这个列表中只会有5个item的UI存在，其它的item都是当被转到可见区时自动把自
			// ** 已的数据实时地更新列UI上，以便查看，也就是说item的UI并不是与后台数据一
			// ** 一对应的，所以正如API文档里说的，convertView并不能确保它总能按你的想法保持不为null
			boolean needCreateItem = (convertView == null);
			// 正在操作的列表行的数据集
			final SODetail rowData = listData.get(position);
			if (needCreateItem)
				// 明细item的UI实例化
				convertView = layoutInflater.inflate(itemResId, null);
			// item里的操作组件实例
			viewProName = (TextView) convertView.findViewById(R.id.common_mall_shop_order_confirm_comment_product_name);
			viewCurrency = (TextView) convertView.findViewById(R.id.common_mall_shop_order_confirm_comment_good_currency);
			viewPrice = (TextView) convertView.findViewById(R.id.common_mall_shop_order_confirm_comment_good_price);
			viewCount = (TextView) convertView.findViewById(R.id.common_mall_shop_order_confirm_comment_count);
			commentBtn = (Button)convertView.findViewById(R.id.common_mall_shop_order_confirm_detail_to_comment);

			// ----------------------------------------------------------------------------------------
			// （2）增加事件处理器
			// 各操作组件的事件监听器只需要在convertView被实例化时才需要重建（convertView需要被实例化
			// 当然就意味着它上面的所有操作组件都已经重新新建了）
			// ** 关于事件处理器的说明：事件处理器的增加其实可以不这么麻烦，直接每getView一次就给组件new一个处理器，
			// ** 这样做的好处是简单，但显然存在资源浪费（每刷新一次view就新建监听器）。而现在的实现就跟Android的列表
			// ** 实现原理一样，在切换到下一组item前，监听器永远只有一屏item的数量（刷新时只需要即时刷新对应item的数据到
			// ** 它的监听器里），这样就节省了资源开销！
			if (needCreateItem)
			{
				//*** 
				CommentOnClickListener commnetListener = new CommentOnClickListener();
				commentBtn.setOnClickListener(commnetListener);
				commentBtn.setTag(commnetListener);
			}

			// ----------------------------------------------------------------------------------------
			// （3）
			// 给标签设置值，以供用户查看
			viewProName.setText(rowData.getDevice_id());
			viewCurrency.setText(String.valueOf(ObjectFactory.createCurrencyTypeRenderer().getNameById(so.getOrder_currency())));
			viewPrice.setText(rowData.getPurchase_price());
			viewCount.setText(MessageFormat.format($$(R.string.common_mall_shop_order_confirm_comment_count), rowData.getPurchase_quantity()));
			
			if("3".equals(so.getOrder_status()) && !rowData.isEvaludated())
			{
				commentBtn.setVisibility(View.VISIBLE);
			}
			else
			{
				commentBtn.setVisibility(View.GONE);
			}
			
			CommentOnClickListener commnetListener = (CommentOnClickListener)commentBtn.getTag();
			commnetListener.setPosition(position);
			
			return convertView;
		}

		@SuppressWarnings("unused")
		public int getSelectedListViewIndex()
		{
			return selectedListViewIndex;
		}

		@SuppressWarnings("unused")
		public void setSelectedListViewIndex(int selectedListViewIndex)
		{
			this.selectedListViewIndex = selectedListViewIndex;
			// this.notifyDataSetChanged();
		}
		
		private class CommentOnClickListener implements View.OnClickListener
		{
			int position = 0;

			public void setPosition(int position)
			{
				this.position = position;
			}

			@Override
			public void onClick(View v)
			{
				soDetail = getItem(position);
				startActivityForResult(IntentFactory.createOrderComfirmCommentActivityIntent(OrderConfirmDetailActivity.this, soDetail), REQUEST_COMMENT_RESULT_INFO);
			}
		}
	}
	
	/**
	 * 重写父类方法为startActivityForResult 服务 接受增加界面传回参数。
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case REQUEST_COMMENT_RESULT_INFO:
				
				if (resultCode == Activity.RESULT_OK)
				{
					System.out.println("============BACK");
					so.getSoDetails().get(current_position).setIs_evaluate("1");
					detailListAdapter.setListData(so.getSoDetails());
					detailListAdapter.notifyDataSetChanged();
					
					Toast.makeText(OrderConfirmDetailActivity.this, R.string.common_mall_shop_order_confirm_detail_comment_success, Toast.LENGTH_LONG).show();
				}
				break;
			default:
				break;
		}
	}
}
